﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Metadata.Edm;
using System.Data.Objects;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Infrastructure.Core
{
    /// <summary>
    ///  ObjectContext扩展方法
    /// </summary>
    public static class ObjectContextExtensions
    {
        /// <summary>
        /// 得到实体键
        /// </summary>
        /// <param name="context"></param>
        /// <param name="entityType"></param>
        /// <returns></returns>
        public static EntitySetBase GetEntitySet(this ObjectContext context, Type entityType)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (entityType == null)
            {
                throw new ArgumentNullException("entityType");
            }

            EntityContainer container =
                context.MetadataWorkspace
                       .GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace);

            if (container == null)
            {
                return null;
            }

            EntitySetBase entitySet =
                container.BaseEntitySets
                         .Where(item => item.ElementType.Name.Equals(entityType.Name))
                         .FirstOrDefault();

            return entitySet;
        }

    }
}
